//
//  TSOpenVideoController.swift
//  TopStock
//
//  Created by dyd on 2017/10/17.
//  Copyright © 2017年 dyd. All rights reserved.
//

import UIKit

class TSOpenVideoController: UIViewController {
    
    @IBOutlet weak var playerBackView: UIView!
    
    @IBOutlet weak var headingContentView: UIView!
    
    @IBOutlet weak var headView: UIView!
    @IBOutlet weak var playerBackViewConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var headTitleLabel: UILabel!
    @IBOutlet weak var headTimeLabel: UILabel!
    @IBOutlet weak var authorLabel: UILabel!
    @IBOutlet weak var contentTextView: UITextView!
    var moveInfoMationDic:NSDictionary? = nil
    var moveUrlStr:String? = nil
    
    
//    // 显示状态栏
    override var prefersStatusBarHidden: Bool {
        return false
    }
    
    // 状态栏设置为白色样式
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    // 隐藏导航栏
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    // 显示导航栏
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        playerView.player.stop()
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "addVideoViewingTime"), object: nil)

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "资讯详情"
        setMoveInformation()
        // 添加视频播放器
        playerBackViewConstraint.constant = view.frame.size.width*(9.0/16.0)
        view.addSubview(playerView)
        playerView.backBtn.isHidden = true
        playerView.frame = CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.size.width*9/16)
        let item = UIBarButtonItem(title: " ", style: .plain, target: self, action: #selector(popViewController))
        item.image = UIImage(named: "backPress")
        self.navigationItem.leftBarButtonItem = item
        self.navigationItem.leftBarButtonItem?.tintColor = BarButtonItemTintColor
    }
    
    func postVideoViewingTime()
    {
        let ms = playerView.player.playerItem.currentTime().seconds * 1000//获取毫秒
        if (ms >= Double(60000)){
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "addVideoViewingTime"), object: ms)
        }
    }
    
    func setMoveInformation()
    {
//        print("author ==>:\(String(describing: moveInfoMationDic?["author"]))")
//        print("click_count ==>:\(String(describing: moveInfoMationDic?["click_count"]))")
//        print("content ==>:\(String(describing: moveInfoMationDic?["content"]))")
//        print("create_time ==>:\(String(describing: moveInfoMationDic?["create_time"]))")
//        print("description ==>:\(String(describing: moveInfoMationDic?["description"]))")
//        print("id ==>:\(String(describing: moveInfoMationDic?["id"]))")
//        print("iftop ==>:\(String(describing: moveInfoMationDic?["iftop"]))")
//        print("title ==>:\(String(describing: moveInfoMationDic?["title"]))")
        
        moveUrlStr = moveInfoMationDic?["url"] as? String
        headTitleLabel.text = moveInfoMationDic?["title"] as? String
        headTimeLabel.adjustsFontSizeToFitWidth = true
        headTimeLabel.minimumScaleFactor=0.6
        
        var time = moveInfoMationDic?["create_time"] as AnyObject
        time = timeStampToString(timeStamp:time.description) as AnyObject
        headTimeLabel.text = NSString.init(format: "时间: %@", time as! CVarArg) as String
        
        let author = moveInfoMationDic?["author"] as? String
        if author != nil{
            authorLabel.text = NSString.init(format: "演讲嘉宾: %@", author!) as String
        }
        let content = moveInfoMationDic?["content"] as? String
        if content != nil{
           contentTextView.text = replacingString(str: content!)
        }
        contentTextView.textAlignment = NSTextAlignment.left
    }

    func replacingString(str:String) -> String
    {
        var tempStr = str
        tempStr = tempStr.replacingOccurrences(of: "&ldquo", with:String("“") )
        tempStr = tempStr.replacingOccurrences(of: "&rdquo", with:String("“") )
        tempStr = tempStr.replacingOccurrences(of: "&mdash", with:String("—") )
       return tempStr
    }
    
    // 视频播放器
    lazy var playerView: LYPlayerView = {
        let playerView = LYPlayerView(url: self.getUrl())
        playerView.assetName = ""
        playerView.delegate = self as? LYPlayerViewDelegate
        return playerView
    }()
    
    
    func getUrl() -> URL
    {
        print("moveUrlStr ==>:\(String(describing: moveUrlStr))")
        let tempUrl = "http://top-stock.oss-cn-hangzhou.aliyuncs.com/4732_b_hd_h264_1280_720.mp4"
        let geturl = tempUrl.addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<> ").inverted)!
        let netURL = URL(string: geturl)
        return netURL!
    }
    
    func timeStampToString(timeStamp:String)->String
    {
        let time = Int(timeStamp)
        let millisecond = Double(time! / 1000)
        let string = NSString(string: millisecond.description)
        let timeSta:TimeInterval = string.doubleValue
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy年MM月dd日 HH:mm:ss"
        let date = NSDate(timeIntervalSince1970: timeSta)
        print(dfmatter.string(from: date as Date))
        return dfmatter.string(from: date as Date)
    }
    
    func popViewController()
    {
        self.navigationController?.popViewController(animated: true)
    }
    
    override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
        if toInterfaceOrientation.isLandscape{
            navigationController?.setNavigationBarHidden(true, animated: true)
            playerView.backBtn.isHidden = false
        }else{
            navigationController?.setNavigationBarHidden(false, animated: true)
            playerView.backBtn.isHidden = true
        }
        headingContentView.isHidden = !playerView.backBtn.isHidden
    }
    override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation)
    {
        if view.frame.size.width > view.frame.size.height
        {
            playerView.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.width*9/16)
        }else{
            playerView.frame = CGRect(x: 0, y: 64, width: view.frame.size.width, height: view.frame.size.width*9/16)
        }
    }
    
}
